﻿using System.Threading;
using System;
using System.Text;
using System.IO;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;
using InTheHand.Net;

namespace DroidPad
{
    class bluetoothConn
    {
        private const int MAX_MESSAGE_SIZE = 2048;
        private Guid ServiceName = new Guid("{fa87c0d0-afac-11de-8a39-0800200c9a66}");
        private BluetoothListener btListener;
        private bool listening = true;
        private BluetoothClient client = null;
        private Stream stream = null;
        private Delegate readDataCallback, connectionClosedCallback;
        private Thread connThread, oldThread = null;
        private int bytesread = 0;
        private Byte[] buffer = new Byte[MAX_MESSAGE_SIZE];
        private ASCIIEncoding asciiE = new ASCIIEncoding();

        public bluetoothConn(Delegate func1, Delegate func2)
        {
            btListener = new BluetoothListener(ServiceName);
            btListener.ServiceName = "cool";
            readDataCallback = func1;
            connectionClosedCallback = func2;
        }

        public void writeData(Byte[] buffer, int BufferLen)
        {
            Stream stream = null;
            try
            {
                stream = client.GetStream();
                stream.Write(buffer, 0, BufferLen);
            }
            catch (Exception) { DPsf.SendErrorMessage("Error Sending (bluetooth)"); return; }
        }

        private String readData(int BufferLen)
        {
        //    try
         //   {           
                bytesread = stream.Read(buffer, 0, BufferLen);
          //  }
           // catch (Exception) { if (listening) { DPsf.SendErrorMessage("Error Sending (bluetooth)"); return null; } }
            if (bytesread == 0)
            {
                DPsf.SendStatMessage("Disconnected...");
                client.Close();
                stream.Close();
                return null;
            }
            return asciiE.GetString(buffer, 0, bytesread); ;
        }

        private void receiveLoop()
        {
           // if (oldThread != null) oldThread.Abort();
            String strReceived;
            client = btListener.AcceptBluetoothClient();
            DPsf.SendStatMessage("Connected-bluetooth");
            stream = client.GetStream();
            strReceived = readData(MAX_MESSAGE_SIZE);
            while (listening)
            {
                if (!client.Connected)
                {
                    DPsf.SendStatMessage("Disconnected...");
                    oldThread = connThread;
                    connectionClosedCallback.DynamicInvoke();
                    oldThread.Abort();
                    //break;
                }
                if (strReceived != "")
                {
                   // DPsf.SendStatMessage(strReceived);
                    readDataCallback.DynamicInvoke(new object[] { connHandler.ConnType.Bluetooth, strReceived });
                    strReceived = readData(MAX_MESSAGE_SIZE);
                }
            }
        }

        public void stop()
        {
            listening = false;
            if (client != null)
                client.Close();
            btListener.Stop();
        }

        public void start()
        {
            listening = true;
            btListener.Start();
            //oldThread = connThread;
            connThread = new Thread(new ThreadStart(delegate() { receiveLoop(); }));
            connThread.Start();
        }

        public void close()
        {
            connThread.Abort();
            stop();
        }
    }
}
